package m202406.d10;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @@author: 爱做梦的锤子
 * @date: 2024/6/10 11:16
 */
public class Q39 {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> res = new ArrayList<>();
        select(target, candidates, 0, new LinkedList<>(), res);
        return res;
    }

    private void select(int target, int[] candidates, int start, LinkedList<Integer> list, List<List<Integer>> res) {
        if (target == 0) {
            res.add(new ArrayList<>(list));
            return;
        }
        for (int i = start; i < candidates.length; i++) {
            if (target - candidates[i] < 0) {
                break;
            }
            list.addLast(candidates[i]);
            select(target - candidates[i], candidates, i, list, res);
            list.removeLast();
        }
    }
}
